import axios from "axios";
import { ElMessage } from "element-plus";

const baseURL = '/blog';
const instance = axios.create({ baseURL });

import { useTokenStore } from "@/stores/token";

//添加请求拦截器
instance.interceptors.request.use(
    (config)=>{
        //请求前的回调
        const tokenStore = useTokenStore();
        if (tokenStore.token) {
            config.headers.Authorization = tokenStore.token
        }
        return config;
    },
    (error) =>{
        return Promise.reject(error);
    }
)

import router from "@/router";

//添加相应拦截器
instance.interceptors.response.use(
    result => {
        if (result.data.code === 0) {
            return result.data;
        }
        ElMessage.error(result.data.message ? result.data.message : '服务异常');
    },
    error => {
        if (error.response.status === 401) {
            ElMessage.error('请先登录')
            router.push('/login')
        } else {
            ElMessage('服务异常');
        }

        return Promise.reject(error);
    }
)

export default instance